package com.example.translateappjava.Fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView; // 导入 ImageView
import android.widget.LinearLayout; // 导入 LinearLayout
import android.widget.TextView;

import com.example.translateappjava.Activity.ThemeUtilsActivity;
import com.example.translateappjava.R;
import com.example.translateappjava.Service.ChatGPT.ChatGptHelper;
import com.example.translateappjava.Utils.Message;
import com.example.translateappjava.Utils.MessageAdapter;
import com.google.android.material.progressindicator.LinearProgressIndicator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ShuaFragment extends Fragment implements ChatGptHelper.OnChatGptResponseListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private final Handler handler = new Handler(Looper.getMainLooper());

    public LinearProgressIndicator linearProgressIndicator;
    private String mParam1;
    private String mParam2;

    public static List<Message> messageList;
    public static MessageAdapter messageAdapter;

    private TextView toolbarTitleTextView; // 用于更改 Toolbar 标题的 TextView
    private ImageView emptyStateBackgroundImage; // 用于显示居中背景图的 ImageView
    private LinearLayout chatContentLayout; // 聊天内容的主布局，方便应用主题
    private RecyclerView recyclerView;

    // 原始标题和“正在输入”时的标题
    private String originalToolbarTitle = "AI Agent";
    private String typingToolbarTitle = "对方正在输入中...";

    public ShuaFragment() {
        // Required empty public constructor
    }

    public static ShuaFragment newInstance(String param1, String param2) {
        ShuaFragment fragment = new ShuaFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shua, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        EditText editTextMessage = view.findViewById(R.id.editTextMessage);
        Button buttonSend = view.findViewById(R.id.buttonSend);
        toolbarTitleTextView = view.findViewById(R.id.toolbar_title);
        emptyStateBackgroundImage = view.findViewById(R.id.empty_state_background_image); // 初始化 ImageView
        chatContentLayout = view.findViewById(R.id.chat_content_layout); // 获取聊天内容布局

        linearProgressIndicator = view.findViewById(R.id.linear_2);
        messageList = new ArrayList<>();
        messageAdapter = new MessageAdapter(messageList);

        // 将主题应用到聊天内容布局上
        // 如果 FrameLayout 只是作为背景图和内容的容器，这样做更好
        ThemeUtilsActivity.applyTheme(chatContentLayout);

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(messageAdapter);

        // 设置初始 Toolbar 标题
        if (toolbarTitleTextView != null) {
            toolbarTitleTextView.setText(originalToolbarTitle);
        }

        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageText = editTextMessage.getText().toString().trim();
                if (!messageText.isEmpty()) {
                    sendMessage(messageText);
                    editTextMessage.setText("");
                }
            }
        });
        linearProgressIndicator.setVisibility(View.INVISIBLE);
        updateBackgroundVisibility(); // 创建视图时检查背景状态
        return view;
    }

    private void sendMessage(String messageText) {
        // 将用户消息添加到列表并通知适配器
        messageList.add(new Message(messageText, true));
        messageAdapter.notifyItemInserted(messageList.size() - 1);
        if (messageList.size() > 0) {
            recyclerView.smoothScrollToPosition(messageList.size() - 1); // 平滑滚动到新消息
        }
        updateBackgroundVisibility(); // 添加消息后检查背景状态

        // AI 开始“输入”
        if (toolbarTitleTextView != null) {
            toolbarTitleTextView.setText(typingToolbarTitle);
        }
        linearProgressIndicator.setVisibility(View.VISIBLE);
        simulateBotResponse(messageText);
    }

    private void simulateBotResponse(String messageText) {
        ChatGptHelper chatGptHelper = new ChatGptHelper(getActivity());
        chatGptHelper.setOnChatGptResponseListener(this); // Fragment 本身处理回调
        chatGptHelper.chatGPTRequest(messageText);
        // 注意：不要在这里隐藏 linearProgressIndicator，它应该在收到响应或错误时隐藏
    }

    @Override
    public void onChatGptResponse(final String response) {
        handler.post(new Runnable() { // 确保 UI 更新在主线程
            @Override
            public void run() {
                // AI 完成输入
                if (toolbarTitleTextView != null) {
                    toolbarTitleTextView.setText(originalToolbarTitle);
                }
                linearProgressIndicator.setVisibility(View.GONE);
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    JSONArray choices = jsonResponse.getJSONArray("choices");
                    JSONObject message = choices.getJSONObject(0).getJSONObject("message");
                    String content = message.getString("content");

                    // 将机器人响应添加到列表并通知适配器
                    messageList.add(new Message(content, false));
                    messageAdapter.notifyItemInserted(messageList.size() - 1);
                    if (messageList.size() > 0) {
                        recyclerView.smoothScrollToPosition(messageList.size() - 1); // 平滑滚动到新消息
                    }
                    updateBackgroundVisibility(); // 添加消息后检查背景状态
                } catch (JSONException e) {
                    e.printStackTrace();
                    // 可选：向用户显示错误信息
                }
            }
        });
    }

    @Override
    public void onError(String message) {
        handler.post(new Runnable() { // 确保 UI 更新在主线程
            @Override
            public void run() {
                // AI 输入出错（也算完成输入过程）
                if (toolbarTitleTextView != null) {
                    toolbarTitleTextView.setText(originalToolbarTitle);
                }
                linearProgressIndicator.setVisibility(View.GONE);
                // 考虑向用户显示错误信息，例如使用 Toast
                // Toast.makeText(getContext(), "错误: " + message, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        // 如果你的主题可以在 Fragment resume 时动态改变，可能需要重新应用
        // if (chatContentLayout != null && getActivity() != null) {
        //     ThemeUtilsActivity.applyTheme(chatContentLayout);
        // }
        updateBackgroundVisibility(); // resumed 时也检查背景状态
    }

    /**
     * 根据消息列表是否为空来更新背景 ImageView 的可见性。
     */
    private void updateBackgroundVisibility() {
        if (emptyStateBackgroundImage == null || messageList == null) {
            return;
        }
        if (messageList.isEmpty()) {
            emptyStateBackgroundImage.setVisibility(View.VISIBLE); // 列表为空，显示背景图
        } else {
            emptyStateBackgroundImage.setVisibility(View.GONE);    // 列表不为空，隐藏背景图
        }
    }
}